package com.clusterswisdom.horn.api.util;

import java.text.ParseException;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.exception.HornApiException;
import com.clusterswisdom.horn.api.ioc.api.ParamType;
import com.clusterswisdom.horn.api.ioc.api.RequestParam;

public class ParamUtil {
	
	public static JSONObject formateInputParam(JSONObject inputParam, List<RequestParam> params) throws Exception {
		if (inputParam == null) {
			return new JSONObject();
		}
		
		JSONObject result = new JSONObject();
		if (params == null || params.size() == 0) {
			return inputParam;
		}
		
		for (RequestParam requestParam : params) {
			if (requestParam.getType() == ParamType.STRUCTFIELDS) {
				continue;
			}
			
			Object value = inputParam.get(requestParam.getName());
			if (value == null && requestParam.isRequired() && requestParam.getDefaultValue() == null) {
				throw new HornApiException("请求参数" + requestParam.getName() + "不能为空!");
			}
			
			String key = requestParam.getName();
			if (requestParam.getMapping() != null) {
				key = requestParam.getMapping();
			}
			
			result.put(key, formateParam(value, requestParam));
		}
		
		return result;
	}

	public static Object formateParam(Object value, RequestParam requestConfig) {
		if (value == null && requestConfig.getDefaultValue() != null) {
			value = requestConfig.getDefaultValue();
		}
		
		if (value == null) {
			return value;
		}
		
		if (requestConfig.getType() == ParamType.STRING) {
			return value.toString();
			
		} else if (requestConfig.getType() == ParamType.NUMBER) {
			return Long.parseLong(value.toString());
			
		} else if (requestConfig.getType() == ParamType.BOOLEAN) {
			return Boolean.parseBoolean(value.toString());
			
		} else if (requestConfig.getType() == ParamType.DATE && value instanceof String) {
			try {
				return DateUtils.parseDate(value.toString(), "yyyy-MM-dd HH:ss:mm");
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
		}
		
		return value;
	}
}
